<template>
  <McLayout class="container">
    <McHeader :title="'证券智能投顾'" :logoImg="''">
      <template #operationArea>
        <div class="operations">
          <i class="icon-helping"></i>
        </div>
      </template>
    </McHeader>
    
    <!-- 导航菜单 -->
    <div class="navigation-tabs">
      <div 
        class="tab-item" 
        :class="{ active: currentTab === 'chat' }"
        @click="switchTab('chat')"
      >
        <i class="icon-chat-line"></i>
        <span>智能咨询</span>
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentTab === 'stockAnalysis' }"
        @click="switchTab('stockAnalysis')"
      >
        <i class="icon-line-chart"></i>
        <span>股票分析</span>
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentTab === 'portfolio' }"
        @click="switchTab('portfolio')"
      >
        <i class="icon-asset"></i>
        <span>投资组合</span>
      </div>
      <div 
        class="tab-item" 
        :class="{ active: currentTab === 'risk' }"
        @click="switchTab('risk')"
      >
        <i class="icon-safety"></i>
        <span>风险评估</span>
      </div>
    </div>
    
    <!-- 内容区域 -->
    <McLayoutContent class="content-container">
      <!-- 聊天界面 -->
      <template v-if="currentTab === 'chat'">
        <div v-if="startPage" style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 20px;">
          <McIntroduction
            :logoImg="''"
            :title="'证券智能投顾'"
            :subTitle="'您好，欢迎使用证券智能投顾服务'"
            :description="description"
          ></McIntroduction>
          <McPrompt
            :list="introPrompt.list"
            :direction="introPrompt.direction"
            class="intro-prompt"
            @itemClick="onSubmit($event.label)"
          ></McPrompt>
        </div>
        <div v-else>
          <template v-for="(msg, idx) in messages" :key="idx">
            <McBubble
              v-if="msg.from === 'user'"
              :content="msg.content"
              :align="'right'"
              :avatarConfig="{ imgSrc: 'https://via.placeholder.com/40x40?text=User' }"
            >
            </McBubble>
            <McBubble v-else :content="msg.content" :avatarConfig="{ imgSrc: 'https://via.placeholder.com/40x40?text=Advisor' }" :loading="msg.loading"> </McBubble>
          </template>
        </div>
      </template>
      
      <!-- 股票分析界面 -->
      <template v-else-if="currentTab === 'stockAnalysis'">
        <StockAnalysisChart />
      </template>
      
      <!-- 投资组合界面 -->
      <template v-else-if="currentTab === 'portfolio'">
        <PortfolioManagement />
      </template>
      
      <!-- 风险评估界面 -->
      <template v-else-if="currentTab === 'risk'">
        <RiskAssessment />
      </template>
    </McLayoutContent>
    
    <!-- 聊天输入区域，只在聊天标签页显示 -->
    <div v-if="currentTab === 'chat'" class="chat-input-area">
      <div class="shortcut" style="display: flex; align-items: center; gap: 8px">
        <McPrompt
          v-if="!startPage"
          :list="simplePrompt"
          :direction="'horizontal'"
          style="flex: 1"
          @itemClick="onSubmit($event.label)"
        ></McPrompt>
        <Button
          v-if="!startPage"
          style="margin-left: auto"
          icon="add"
          shape="circle"
          title="新建对话"
          size="md"
          @click="newConversation"
        />
      </div>
      <McLayoutSender>
        <McInput :value="inputValue" :maxLength="2000" @change="(e: string) => (inputValue = e)" @submit="onSubmit">
          <template #extra>
            <div class="input-foot-wrapper">
              <div class="input-foot-left">
                <span v-for="(item, index) in inputFootIcons" :key="index">
                  <i :class="item.icon"></i>
                  {{ item.text }}
                </span>
                <span class="input-foot-dividing-line"></span>
                <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
              </div>
              <div class="input-foot-right">
                <Button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''"><span class="demo-button-content">清空输入</span></Button>
              </div>
            </div>
          </template>
        </McInput>
      </McLayoutSender>
    </div>
  </McLayout>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { Button } from 'vue-devui/button';
import 'vue-devui/button/style.css';
import OpenAI from 'openai';
import StockAnalysisChart from './components/StockAnalysisChart.vue';
import PortfolioManagement from './components/PortfolioManagement.vue';
import RiskAssessment from './components/RiskAssessment.vue';

const description = [
  '证券智能投顾可以为您提供股票分析、投资组合管理、市场趋势分析、风险评估等证券投资咨询服务。',
  '作为智能投顾，我们将竭诚为您提供专业、高效的投资建议，但请注意投资有风险，入市需谨慎。',
];
const introPrompt = {
  direction: 'horizontal',
  list: [
    {
      value: 'stockAnalysis',
      label: '股票分析方法',
      iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
      desc: '如何分析股票基本面和技术面',
    },
    {
      value: 'portfolioManagement',
      label: '投资组合管理',
      iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
      desc: '如何构建和优化投资组合',
    },
    {
      value: 'riskAssessment',
      label: '风险评估方法',
      iconConfig: { name: 'icon-priority', color: '#3ac295' },
      desc: '投资风险评估和管理策略',
    },
  ],
};
const simplePrompt = [
  {
    value: 'stockAnalysis',
    iconConfig: { name: 'icon-info-o', color: '#5e7ce0' },
    label: '股票分析方法',
  },
  {
    value: 'portfolioManagement',
    iconConfig: { name: 'icon-star', color: 'rgb(255, 215, 0)' },
    label: '投资组合管理',
  },
  {
    value: 'riskAssessment',
    iconConfig: { name: 'icon-priority', color: '#3ac295' },
    label: '风险评估方法',
  },
  {
    value: 'marketTrends',
    iconConfig: { name: 'icon-line-chart', color: '#e74c3c' },
    label: '市场趋势分析',
  },
];
const startPage = ref(true);
const inputValue = ref('');
const currentTab = ref('chat'); // 可选值: 'chat', 'stockAnalysis', 'portfolio', 'risk'
const inputFootIcons = [
  { icon: 'icon-at', text: '智能体' },
  { icon: 'icon-standard', text: '词库' },
  { icon: 'icon-add', text: '附件' },
];

const switchTab = (tab: string) => {
  currentTab.value = tab;
};

const messages = ref<any[]>([]);

// DeepSeek API配置
const client = ref<OpenAI>();

client.value = new OpenAI({
  apiKey: import.meta.env.VITE_DEEPSEEK_API_KEY || '', // 从环境变量读取API Key
  baseURL: import.meta.env.VITE_DEEPSEEK_BASE_URL || 'https://api.deepseek.com', // 从环境变量读取Base URL
  dangerouslyAllowBrowser: true, // 浏览器环境使用需要开启
});

const newConversation = () => {
  startPage.value = true;
  messages.value = [];
}

const onSubmit = (evt: Event) => {
  evt.preventDefault();
  if (!inputValue.value.trim()) return;
  
  const userMessage = inputValue.value.trim();
  inputValue.value = '';
  startPage.value = false;
  messages.value.push({
    from: 'user',
    content: userMessage,
    avatarConfig: { name: 'user' },
  });
  
  fetchData(userMessage);
};

const fetchData = async (ques: string) => {
  messages.value.push({
    from: 'model',
    content: '',
    avatarConfig: { name: 'model' },
    id: '',
    loading: true,
  });
  try {
    // 使用fetch API直接调用DeepSeek API，避免OpenAI SDK版本兼容性问题
    const response = await fetch(import.meta.env.VITE_DEEPSEEK_BASE_URL + '/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: 'deepseek-reasoner',
        messages: [
          {
            role: 'system',
            content: '你是一名专业的证券智能投顾，负责为投资者提供股票分析、投资组合管理、市场趋势分析、风险评估等证券投资咨询服务。请使用专业、客观的语言回答客户问题，提供有价值的投资参考信息。请务必在回答中包含风险提示："投资有风险，入市需谨慎"。如果遇到不确定的问题或超出能力范围的问题，请明确告知用户并建议其咨询专业的证券顾问。'
          },
          { role: 'user', content: ques }
        ],
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    messages.value[messages.value.length - 1].loading = false;

    // 处理流式响应
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('No response body');
    }

    const decoder = new TextDecoder('utf-8');
    let accumulatedContent = '';
    let chatId = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n').filter(line => line.trim() !== '');

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.substring(6);
          if (data === '[DONE]') {
            break;
          }
          try {
            const json = JSON.parse(data);
            if (json.id) {
              chatId = json.id;
              messages.value[messages.value.length - 1].id = chatId;
            }
            if (json.choices && json.choices.length > 0) {
              const delta = json.choices[0].delta;
              if (delta && delta.content) {
                accumulatedContent += delta.content;
                messages.value[messages.value.length - 1].content = accumulatedContent;
              }
            }
          } catch (e) {
            console.error('解析流式数据错误:', e);
          }
        }
      }
    }
  } catch (error) {
    console.error('DeepSeek API调用错误:', error);
    messages.value[messages.value.length - 1].content = '抱歉，模型调用失败，请稍后重试。';
    messages.value[messages.value.length - 1].loading = false;
  }
};
</script>

<style>
/* 全局样式变量 */
:root {
  --primary-color: #0066cc;
  --primary-light: #4da6ff;
  --primary-dark: #004d99;
  --success-color: #00a86b;
  --danger-color: #ff4d4f;
  --warning-color: #faad14;
  --text-primary: #333333;
  --text-secondary: #666666;
  --text-muted: #999999;
  --bg-primary: #ffffff;
  --bg-secondary: #f5f7fa;
  --border-color: #e0e0e0;
  --shadow-light: 0 2px 8px rgba(0, 0, 0, 0.08);
  --shadow-medium: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 主容器样式 */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  height: 100vh;
  padding: 16px;
  gap: 12px;
  background: var(--bg-secondary);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-light);
}

/* 头部样式增强 */
:deep(.mc-header) {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)) !important;
  color: white !important;
  border-radius: 8px;
  padding: 0 24px !important;
  height: 64px !important;
  box-shadow: var(--shadow-light);
}

:deep(.mc-header-title) {
  color: white !important;
  font-size: 1.3rem !important;
  font-weight: 600 !important;
}

/* 内容区域样式 */
.content-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: auto;
  flex: 1;
  padding: 24px;
  background: var(--bg-primary);
  border-radius: 8px;
  box-shadow: var(--shadow-light);
  border: 1px solid var(--border-color);
}

/* 导航标签样式 */
.navigation-tabs {
  display: flex;
  background: var(--bg-primary);
  border-radius: 8px;
  padding: 6px;
  box-shadow: var(--shadow-light);
  margin-bottom: 0;
  border: 1px solid var(--border-color);
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 14px 8px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 500;
  position: relative;
  overflow: hidden;
}

.tab-item:hover {
  background-color: var(--bg-secondary);
  color: var(--primary-color);
  transform: translateY(-1px);
}

.tab-item.active {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
  color: white;
  box-shadow: 0 2px 6px rgba(0, 102, 204, 0.3);
}

.tab-item i {
  margin-bottom: 6px;
  font-size: 18px;
  transition: transform 0.3s ease;
}

.tab-item.active i {
  transform: scale(1.1);
}

/* 聊天输入区域样式 */
.chat-input-area {
  margin-top: 0;
  background: var(--bg-primary);
  border-radius: 8px;
  padding: 16px;
  box-shadow: var(--shadow-light);
  border: 1px solid var(--border-color);
}

/* 自定义气泡样式 */
:deep(.mc-bubble) {
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 12px;
  max-width: 80%;
  font-size: 15px;
  line-height: 1.6;
  word-wrap: break-word;
}

:deep(.mc-bubble-right) {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)) !important;
  color: white !important;
  border-bottom-right-radius: 4px !important;
}

:deep(.mc-bubble-left) {
  background: var(--bg-secondary) !important;
  color: var(--text-primary) !important;
  border-bottom-left-radius: 4px !important;
  border: 1px solid var(--border-color);
}

:deep(.mc-bubble-avatar) {
  width: 36px !important;
  height: 36px !important;
  border-radius: 50% !important;
}

/* 介绍卡片样式 */
:deep(.mc-introduction) {
  background: linear-gradient(135deg, #f0f7ff, #e0f2fe);
  border-radius: 12px;
  padding: 24px;
  border: 1px solid var(--primary-light);
  box-shadow: var(--shadow-light);
}

:deep(.mc-introduction-title) {
  color: var(--primary-dark) !important;
  font-size: 1.8rem !important;
  font-weight: 600 !important;
  margin-bottom: 8px !important;
}

:deep(.mc-introduction-subtitle) {
  color: var(--text-secondary) !important;
  font-size: 1.1rem !important;
  margin-bottom: 16px !important;
}

:deep(.mc-introduction-description) {
  color: var(--text-secondary) !important;
  font-size: 1rem !important;
  line-height: 1.7 !important;
}

/* 提示卡片样式 */
:deep(.mc-prompt-item) {
  border: 1px solid var(--border-color) !important;
  border-radius: 8px !important;
  padding: 16px !important;
  transition: all 0.3s ease !important;
  background: var(--bg-primary) !important;
}

:deep(.mc-prompt-item:hover) {
  border-color: var(--primary-color) !important;
  box-shadow: 0 2px 8px rgba(0, 102, 204, 0.15) !important;
  transform: translateY(-2px) !important;
}

:deep(.mc-prompt-item-icon) {
  font-size: 1.5rem !important;
  margin-bottom: 8px !important;
}

:deep(.mc-prompt-item-label) {
  font-weight: 600 !important;
  color: var(--text-primary) !important;
  margin-bottom: 4px !important;
}

:deep(.mc-prompt-item-desc) {
  color: var(--text-secondary) !important;
  font-size: 0.9rem !important;
}

/* 输入框样式 */
:deep(.mc-input) {
  border-radius: 8px !important;
  border: 2px solid var(--border-color) !important;
  transition: border-color 0.3s ease, box-shadow 0.3s ease !important;
}

:deep(.mc-input:focus) {
  border-color: var(--primary-color) !important;
  box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.1) !important;
  outline: none !important;
}

:deep(.mc-layout-sender) {
  background: var(--bg-primary) !important;
  border-radius: 8px !important;
}

/* 按钮样式增强 */
:deep(.devui-btn-primary) {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark)) !important;
  border: none !important;
  color: white !important;
  border-radius: 6px !important;
  transition: all 0.3s ease !important;
}

:deep(.devui-btn-primary:hover) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3) !important;
}

:deep(.devui-btn-secondary) {
  background: var(--bg-secondary) !important;
  border: 1px solid var(--border-color) !important;
  color: var(--text-primary) !important;
}

:deep(.devui-btn-secondary:hover) {
  border-color: var(--primary-color) !important;
  background: var(--bg-primary) !important;
}

/* 输入底部工具栏样式 */
.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;
  padding-top: 8px;

  .input-foot-left {
    display: flex;
    align-items: center;
    gap: 12px;

    span {
      font-size: 14px;
      line-height: 18px;
      color: var(--text-secondary);
      cursor: pointer;
      transition: color 0.3s ease;
    }

    span:hover {
      color: var(--primary-color);
    }

    .input-foot-dividing-line {
      width: 1px;
      height: 16px;
      background-color: var(--border-color);
    }

    .input-foot-maxlength {
      font-size: 13px;
      color: var(--text-muted);
    }
  }

  .input-foot-right {
    .demo-button-content {
      font-size: 14px;
    }

    & > *:not(:first-child) {
      margin-left: 8px;
    }
  }
}

/* 风险提示样式 */
.risk-warning {
  border-left: 4px solid var(--warning-color);
  padding: 12px 16px;
  background-color: #fff7e6;
  color: var(--text-primary);
  font-size: 0.9rem;
  margin: 16px 0;
  border-radius: 0 6px 6px 0;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .container {
    max-width: 100%;
    margin: 0;
    border-radius: 0;
    height: 100vh;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 8px;
    height: 100vh;
  }
  
  .content-container {
    padding: 16px;
  }
  
  :deep(.mc-header) {
    padding: 0 16px !important;
    height: 56px !important;
  }
  
  :deep(.mc-header-title) {
    font-size: 1.1rem !important;
  }
  
  .navigation-tabs {
    padding: 4px;
    overflow-x: auto;
    scrollbar-width: none;
  }
  
  .navigation-tabs::-webkit-scrollbar {
    display: none;
  }
  
  .tab-item {
    min-width: 90px;
    flex-shrink: 0;
    padding: 12px 6px;
  }
  
  .tab-item span {
    font-size: 12px;
  }
  
  .tab-item i {
    font-size: 16px;
    margin-bottom: 4px;
  }
  
  :deep(.mc-bubble) {
    max-width: 85%;
    padding: 10px 14px;
    font-size: 14px;
  }
  
  .chat-input-area {
    padding: 12px;
  }
  
  :deep(.mc-prompt-item) {
    padding: 12px !important;
  }
}

/* 股票上涨下跌颜色类 */
.stock-up {
  color: var(--danger-color) !important;
}

.stock-down {
  color: var(--success-color) !important;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

:deep(.mc-bubble) {
  animation: fadeIn 0.3s ease-out;
}

/* 滚动条美化 */
.content-container::-webkit-scrollbar {
  width: 6px;
}

.content-container::-webkit-scrollbar-track {
  background: var(--bg-secondary);
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb {
  background: var(--text-muted);
  border-radius: 3px;
  transition: background 0.3s ease;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}
</style>